package com.wmsafe.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class CorsFilter implements GlobalFilter, Ordered {

    private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN , token";
    private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 添加允许的来源头
        exchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
        // 添加允许的方法
        exchange.getResponse().getHeaders().add("Access-Control-Allow-Methods", ALLOWED_METHODS);
        // 添加允许的请求头
        exchange.getResponse().getHeaders().add("Access-Control-Allow-Headers", ALLOWED_HEADERS);

        if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
            // 如果是OPTIONS请求，则返回200状态码并立即结束请求
            exchange.getResponse().setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }

        // 继续向下执行过滤器链
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 设置过滤器的优先级，数值越小优先级越高
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
